<template>
  <div>
    <wk-page-header
      :title="config.showModuleName ? $t('crm.invoice.6fd7414c05df94e9deec0b47b60ecd34') : ''"
      :help="getHelpObj(crmType, 'index')"
      :dropdowns="getDefaultHeaderHandes()"
      @command="pageHeaderCommand">
      <template slot="right">
        <el-button
          v-if="saveAuth"
          type="primary"
          @click="createClick">{{ $t('crm.invoice.c0acda86d2de311d70ed854a32e9ebb7') }}</el-button>
      </template>
    </wk-page-header>
    <div
      v-empty="!indexAuth"
      xs-empty-icon="nopermission"
      :xs-empty-text="$t('crm.invoice.8da17a43fc2ba3e14af83bd3e6b82609')"
      class="crm-container">
      <wk-table-header
        :search.sync="search"
        :tabs="sceneList"
        :active-tab.sync="sceneId"
        :selection-list="tableSelectionList"
        :operations="handleOperations"
        :condition-type-fun="undefined"
        :fields="getFilterFields"

        :props="tableHeaderProps.props"
        :filter-header-props="tableHeaderProps.filterHeaderProps"
        :filter-form-props="tableHeaderProps.filterFormProps"
        :scene-set-props="tableHeaderProps.sceneSetProps"
        :scene-create-props="tableHeaderProps.sceneCreateProps"
        @tabs-change="sceneSelect"
        @operations-click="tableOperationsClick"
        @event-change="tableHeaderHandle"
        @filter-change="handleFilter"
      >
        <template v-if="tableStyleObj.viewType === '2'" slot="custom">
          <el-select
            v-model="activeFlow"
            value-key="flowId"
            class="flow-wrapper">
            <el-option
              v-for="flow in flowList"
              :key="flow.flowId"
              :label="flow.flowName"
              :value="flow" />
          </el-select>
        </template>

        <wk-toggle-button
          v-if="activeFlow"
          v-model="tableStyleObj.viewType">
          <wk-toggle-item value="1">
            <i class="wk wk-icon-three-line" />
          </wk-toggle-item>
          <wk-toggle-item value="2">
            <i class="wk wk-icon-org-solid" />
          </wk-toggle-item>
        </wk-toggle-button>
      </wk-table-header>

      <stage-view
        v-if="tableStyleObj.viewType === '2' && activeFlow"
        :key="`${activeFlow.flowId}${refreshKey}`"
        :base-params="baseParams"
        :flow-item="activeFlow"
        @enter-detail="enterDetail" />

      <template v-else>
        <el-table
          id="crm-table"
          v-loading="loading"
          :row-height="rowHeight"
          :data="list"
          :height="tableHeight"
          :cell-class-name="cellClassName"
          :row-key="`${crmType}Id`"
          :class="crmTableClass"
          :stripe="tableStyleObj.stripe"
          use-virtual
          highlight-current-row
          style="width: 100%;"
          @row-click="handleRowClick"
          @sort-change="sortChange"
          @header-dragend="handleHeaderDragend"
          @selection-change="handleSelectionChange">
          <el-table-column
            show-overflow-tooltip
            reserve-selection
            type="selection"
            fixed
            align="center"
            width="55" />
          <el-table-column
            fixed
            width="60">
            <template
              slot="header"
              slot-scope="{}">
              <i class="el-icon-star-off focus-icon is-disabled" />
            </template>
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.star == 0 ? '添加关注' : '取消关注'" effect="dark" placement="top">
                <i
                  v-if="scope.row.star == 0"
                  class="el-icon-star-off focus-icon"
                  @click="toggleStar(scope.row)" />
                <i
                  v-else
                  class="wk wk-focus-on focus-icon active"
                  @click="toggleStar(scope.row)" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in showfieldList"
            :key="index"
            :fixed="item.isLock === 1"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :class-name="item.width>60 ? 'column' : '' "
            sortable="custom"
            show-overflow-tooltip>
            <template v-if="item.width>60" slot="otherHeader">
              <el-button
                :icon="item.isLock === 1 ? 'wk wk-unlock' : 'wk wk-lock'"
                class="el-lock-btn"
                type="text"
                @click.stop="fieldFixed(item)" />
              <el-button
                v-if="showFilter(item)"
                class="el-filter-btn"
                type="text"
                icon="wk wk-screening"
                @click.stop="showFilterClick(item)" />
            </template>
            <template slot-scope="{ row, column }">
              <template v-if="item.prop == 'checkStatus'">
                <span :style="getStatusStyle(row.checkStatus)" class="status-mark" />
                <span>{{ getStatusName(row.checkStatus) }}</span>
              </template>
              <template v-else-if="item.prop == 'invoiceType'">
                {{ fieldFormatter(row, column, row[column.property], item) }}
              </template>
              <wk-field-view
                v-else
                :props="item"
                :form-type="item.formType"
                :value="row[column.property]">
                {{ fieldFormatter(row, column, row[column.property], item) }}
              </wk-field-view>
            </template>
          </el-table-column>
          <el-table-column />
          <el-table-column
            v-if="canUpdateStatus"
            :resizable="false"
            :label="$t('crm.invoice.83afedd2c3fe8408d6a830e13a9ac15c')"
            fixed="right"
            width="150">
            <template slot-scope="scope">
              <el-button
                :disabled="scope.row.invoiceStatus == 1"
                type="primary-text"
                style="padding: 0;"
                @click.native="markReceivables(scope)">{{ scope.row.invoiceStatus == 1 ? $t('crm.invoice.48081466b0b262e435ec23124fe3dc0f'):$t('crm.invoice.eab0ad4d8ed77eb356378d872fde9def') }}</el-button>
            </template>
          </el-table-column>

          <wk-empty
            slot="empty"
            :props="{
              buttonTitle: $t('crm.invoice.5b3da211f0b978b0ab5d1e00f01e0cb1'),
              showButton: saveAuth
            }"
            @click="createClick"
          />
          <field-set
            slot="other"
            :crm-type="crmType"
            @change="setSave" />
        </el-table>
        <div class="p-contianer">
          <el-dropdown trigger="click" placement="top">
            <el-button class="dropdown-btn"><i class="el-icon-s-fold" /></el-button>
            <el-dropdown-menu slot="dropdown" class="wk-table-style-dropdown-menu">
              <el-dropdown-item>
                <span @click.stop><el-switch v-model="tableStyleObj.rightBorderShow" />{{ $t('crm.invoice.73e689fda124b139b7e57c81852c7ee2') }}</span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click.stop><el-switch v-model="tableStyleObj.bottomBorderShow" />{{ $t('crm.invoice.cb9aed63c80c69db0a8a1de30d50c079') }}</span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click.stop><el-switch v-model="tableStyleObj.stripe" />{{ $t('crm.invoice.9563affde39446d0c476d5948dab2b04') }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-pagination
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size.sync="pageSize"
            :total="total"
            :pager-count="5"
            class="p-bar"
            layout="prev, pager, next, sizes, total, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
          <span class="money-bar">{{ moneyDes }}</span>
        </div>
      </template>
    </div>

    <create
      v-if="isCreate"
      @save-success="refreshList"
      @close="isCreate = false" />
    <mark-invoice
      v-if="markShow"
      :visible.sync="markShow"
      :reset="isResetInvoice"
      :detail="rowDetail"
      @change="handleHandle({
        type: 'reset_invoice_status'
      })"
    />

    <!-- 相关详情页面 -->
    <c-r-m-all-detail
      :id.sync="rowID"
      :visible.sync="showDview"
      :crm-type="rowType"
      :page-list="crmType == rowType ? list : []"
      :page-index.sync="rowIndex"
      class="d-view"
      @handle="handleHandle" />

    <!-- 转移 -->
    <transfer-handle
      v-if="transferDialogShow"
      :props="transferHandleProps"
      :dialog-visible.sync="transferDialogShow"
      @handle="handleHandle" />
  </div>
</template>

<script>
import {
  crmInvoiceDeleteIdsAPI,
  crmInvoiceTransferAPI,
  crmInvoiceBatchExcelExportAPI
} from '@/api/crm/invoice'

import Create from './Create'
import MarkInvoice from './components/MarkInvoice'
import TransferHandle from '@/components/Page/SelectionHandle/TransferHandle' // 转移
import CRMAllDetail from '@/views/crm/components/CRMAllDetail'

import TableMixin from '../mixins/Table'
import { getFormFieldShowName } from '@/components/NewCom/WkForm/utils'
import { floatAdd } from '@/utils'
import { separator } from '@/filters/vueNumeralFilter/filters'

export default {
  name: 'Invoice', // 发票
  components: {
    Create,
    MarkInvoice,
    TransferHandle,
    CRMAllDetail
  },
  mixins: [TableMixin],
  props: {},
  data() {
    return {
      crmType: 'invoice',
      list: [],
      selectionList: [], // 勾选数据 用于全局导出
      isCreate: false,
      rowDetail: {},
      markShow: false,
      isResetInvoice: false,
      moneyData: null, // 列表金额

      // 转移
      transferHandleProps: {},
      transferDialogShow: false
    }
  },
  computed: {
    // 选择数据，隐藏金额信息
    showBottomMoney() {
      return !this.config.isSelect
    },

    moneyDes() {
      // 选择数据，隐藏金额信息
      if (!this.showBottomMoney) {
        return ''
      }

      if (!this.moneyData || JSON.stringify(this.moneyData) == '{}') {
        return ''
      }

      const canCheckMoney = this.moneyData.hasOwnProperty('contractMoney')
      const canCheckInvoiceMoney = this.moneyData.hasOwnProperty('invoiceMoney')
      let contractMoney = 0.0
      let invoiceMoney = 0.0

      // 未勾选展示合同总金额信息
      if (this.selectionList.length == 0) {
        contractMoney = this.moneyData.contractMoney || 0
        invoiceMoney = this.moneyData.invoiceMoney || 0
      } else {
        for (let index = 0; index < this.selectionList.length; index++) {
          const element = this.selectionList[index]
          // 1 审核通过的合同 10 正常
          if ([1, 10].includes(Number(element.checkStatus))) {
            if (canCheckMoney) {
              contractMoney = floatAdd(contractMoney, parseFloat(element.contractMoney || 0))
            }
            if (canCheckInvoiceMoney) {
              invoiceMoney = floatAdd(invoiceMoney, parseFloat(element.invoiceMoney || 0))
            }
          }
        }

        contractMoney = contractMoney.toFixed(2)
        invoiceMoney = invoiceMoney.toFixed(2)
      }

      let moneyDes = ''
      if (canCheckMoney) {
        moneyDes = `合同总金额：${separator(this.crmMoney(contractMoney || 0))}` + this.crmMoneyUnit
      }

      if (canCheckInvoiceMoney) {
        moneyDes += moneyDes ? ' / ' : ''
        moneyDes += `发票金额：${separator(this.crmMoney(invoiceMoney || 0))}` + this.crmMoneyUnit
      }

      return moneyDes
    },
    // 是否能操作
    canUpdateStatus() {
      return this.crm && this.crm[this.crmType] && this.crm[this.crmType].updateInvoiceStatus
    },
    showfieldList() {
      return this.fieldList.filter(item => item.prop !== 'invoiceStatus')
    },
    // 可操作选项
    handleOperations() {
      return this.getOperations([
        'delete',
        'reset_invoice_status',
        'transfer',
        'export'
      ])
    }
  },
  watch: {},
  created() {
  },

  beforeDestroy() {},
  methods: {
    /**
     * @description: 表头事件
     * @param {*} type
     * @return {*}
     */
    tableOperationsClick(type) {
      if (type === 'transfer') {
        this.transferHandleProps = {
        // 场景编辑请求
          request: crmInvoiceTransferAPI,
          params: { ids: this.selectionList.map(item => item[this.crmType + 'Id']) },
          showRemoveType: false, // 是否展示移除操作类型
          // 帮助提示
          help: this.getHelpObj(this.crmType, 'transfer')
        }
        this.transferDialogShow = true
      } else if (type == 'delete') {
        this.$confirm(
          this.$t('crm.invoice.6226a155b2c5fcedcdfaab67c9d13b02'),
          this.$t('crm.invoice.24817fb4b6ce5d84f4498fd5bda62334'),
          {
            confirmButtonText: this.$t('crm.invoice.20e107460c0c358bd8d63035b9b6f4fe'),
            cancelButtonText: this.$t('crm.invoice.e8cb7ab6d7cca944c247bf2497558706'),
            type: 'warning'
          }
        )
          .then(() => {
            this.loading = true
            crmInvoiceDeleteIdsAPI(this.selectionList.map(item => item.invoiceId))
              .then(res => {
                this.loading = false
                this.$message({
                  type: 'success',
                  message: this.$t('crm.invoice.26bbea5d4cdd281a30982d808d1c0206')
                })
                this.handleHandle({
                  type: 'delete'
                })
              })
              .catch(() => {
                this.loading = false
              })
          })
          .catch(() => {})
      } else if (type == 'reset_invoice_status') {
        this.rowDetail = this.selectionList[0]
        this.isResetInvoice = true
        this.markShow = true
      } else if (type === 'export') {
        // 勾选导出
        this.$wkExport.export(this.crmType, {
          ...this.getExportFieldRequestData(),
          params: { ids: this.selectionList.map(item => item[`${this.crmType}Id`]) },
          request: crmInvoiceBatchExcelExportAPI
        })
      }
    },

    /**
     * 创建点击
     */
    createClick() {
      this.isCreate = true
    },

    /**
     * 格式化字段
     */
    fieldFormatter(row, column, cellValue, field) {
      if (field) {
        return getFormFieldShowName(field.formType, row[column.property])
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },

    /**
     * 开票操作
     */
    markReceivables(scope) {
      this.rowDetail = scope.row
      this.isResetInvoice = false
      this.markShow = true
    },

    /**
     * 改变负责人筛选条件
     */
    changeUserCell(data) {
      this.filterParams.ownerUserId = data.value
      this.refreshList()
    },

    /**
     * 列表操作
     */
    handleCommand(command) {

    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'invoiceApplyNumber') {
        return 'can-visit--underline can-visit--bold'
      } else if (
        column.property === 'customerName' ||
        column.property === 'contractNum' ||
        column.property === 'receivablesNum'
      ) {
        return 'can-visit--underline'
      } else {
        return ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/table.scss";

.field-set-wrap {
  z-index: 10;
}
</style>
